package com.nativetalk.service.teacher.record;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.ClassRoom;
import com.nativetalk.bean.recording.TdNtMembRecordingList;
import com.nativetalk.bean.teacher.TeacherRecordUploadRequest;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.oss.OssUtil;
import com.nativetalk.dao.TdNtCourseInstanceRecordingDao;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Micoo on 2017/3/9.
 */
@Service
public class TeacherRecordService {

    private static Logger logger = Logger.getLogger(TeacherRecordService.class);
    private static String recordingStorePath = Constants.FILE + "/" + Constants.FILEIMG + "/course/recording";

    @Resource
    private TdNtCourseInstanceRecordingDao tdNtCourseInstanceRecordingDao;

    public RetInfo uploadRecording(Integer tea_id, TeacherRecordUploadRequest uploadRequest) {
        logger.info("====== uploadRecording  begin======");
        RetInfo retInfo = new RetInfo();

        try {
            //1. 上传图片到阿里云存储
            CommonsMultipartFile file = uploadRequest.getRecordFile();

            ObjectMetadata objectMetadata_picture = new ObjectMetadata();
            objectMetadata_picture.setContentLength(file.getSize());

            ClassRoom classRoom = tdNtCourseInstanceRecordingDao.findClassRoomById(uploadRequest.getRoomId());

            if (classRoom == null) {
                retInfo.setMark("-1");
                retInfo.setTip("Invalid roomId:" + uploadRequest.getRoomId());
                return retInfo;
            }

            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).replace("wa v", "wav");//文件后缀名
            String pathname = recordingStorePath + "/" + classRoom.getRoom_id() + "/" + tea_id + "-" + UUID.randomUUID().toString() + suffix;
            OssUtil.uploadInputStream(uploadRequest.getRecordFile().getInputStream(), objectMetadata_picture, pathname);

            //获取音频时长，如果读取失败，设置音频时长为0
            long duration = 0;//音频时长，单位：秒
            DiskFileItem dfi = (DiskFileItem) file.getFileItem();
            File source = dfi.getStoreLocation();
            Encoder encoder = new Encoder();
            try {
                MultimediaInfo m = encoder.getInfo(source);
                long ls = m.getDuration();
                duration = ls / 1000;
            } catch (InputFormatException e) {
                logger.error("读取音频文件时长失败", e);
            } catch (EncoderException e) {
                logger.error("读取音频文件时长失败", e);
            } catch (Exception e) {
                logger.error("读取音频文件时长失败", e);
            }
            Integer maxSequence = tdNtCourseInstanceRecordingDao.findSequenceByRoomId(classRoom.getRoom_id());
            if (maxSequence == null) {
                maxSequence = 0;
            }
            TdNtMembRecordingList record = new TdNtMembRecordingList();
            record.setFile_size(file.getSize());
            record.setTea_id(tea_id);
            record.setMemb_id(classRoom.getMemb_id());
            record.setRoom_id(classRoom.getRoom_id());
            record.setType(1);//在评论是显示录音
            record.setSequence(maxSequence + 1);
            record.setRecording_url(pathname);
            record.setDuration(duration);
            Date now = new Date();
            record.setInsert_date(now);
            record.setUpdate_date(now);
            tdNtCourseInstanceRecordingDao.save(record);

            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("录音上传成功");
            Map<String, Object> map = new HashMap<>();
            map.put("recording_url", pathname);
            retInfo.setObj(map);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR") + ",错误描述:" + e.getMessage());
        }
        logger.info("====== uploadRecording  end======");
        return retInfo;
    }

    public static void main(String[] args) {
        long duration = 0;//音频时长，单位：秒
        //1121-297031a7-3328-4db0-84e0-3175ec6eed4a.wav
        //201603282212513.mp3
        File file = new File("d:/1121-297031a7-3328-4db0-84e0-3175ec6eed4a.wav");
        Encoder encoder = new Encoder();
        try {
            MultimediaInfo m = encoder.getInfo(file);
            long ls = m.getDuration();
            duration = ls / 1000;
            System.out.println(m.getFormat());
            System.out.println(m.getAudio().toString());
        } catch (InputFormatException e) {
            logger.error("读取音频文件时长失败", e);
        } catch (EncoderException e) {
            logger.error("读取音频文件时长失败", e);
        }
        System.out.println(duration);

    }

}
